package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"time"

	pb "grpc_demo/grpc_error/grpc_error"
)

func main() {
	// 建立连接
	conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// 客户端
	c := pb.NewGreeterClient(conn)

	ctx, _ := context.WithTimeout(context.Background(), time.Second*3) //通过context实现server api服务超时机制
	_, err = c.SayHello(ctx, &pb.HelloRequest{Name: "bobby"})
	if err != nil {
		// 判断是否是grpc内的status error
		st, ok := status.FromError(err)
		if !ok {
			// Error was not a status error
			panic("解析error失败")
		}
		fmt.Println(st.Message()) //error message
		fmt.Println(st.Code())    //error code
	}
}
